﻿#region

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.Extensions.DependencyInjection;
using Vin.Extension.Exception.Interface;
using Vin.Extension.Exception.Middleware;
using Vin.Tool.Core.AssemblyCategory;

#endregion

namespace Vin.Extension.Exception;

[Order(10)]
public class ExtensionEntry : IVinExtension
{
    private readonly List<Type> _exceptionHandlerTypes;
    
    private readonly List<Type> _notifyExceptionHandlerTypes;

    public ExtensionEntry()
    {
        _exceptionHandlerTypes = AssemblyTool.GetTypes<IExceptionHandler>();
        _notifyExceptionHandlerTypes = AssemblyTool.GetTypes<IExceptionNotifyHandler>();
    }

    public void AddVinExtension(WebApplicationBuilder builder)
    {
        _exceptionHandlerTypes.ForEach(type => { builder.Services.AddSingleton(typeof(IExceptionHandler), type); });
        _notifyExceptionHandlerTypes.ForEach(type => { builder.Services.AddScoped(typeof(IExceptionNotifyHandler), type); });
    }

    public void AddVinExtension(IServiceCollection services)
    {
    }

    public void UseVinExtension(WebApplication app)
    {
        app.UseMiddleware<MicrosoftExceptionMiddleware>();
        // 注册异常处理
        app.UseExceptionHandler(new ExceptionHandlerOptions()
        {
            ExceptionHandler = ExceptionTool.DefaultExceptionHandlerAsync
        });
    }
}